<?php
/**
 * @package JoiCaddy
 * @copyright Авторские права (C) 2008-2010 Joostina team. Все права защищены.
 * @license Лицензия http://www.gnu.org/licenses/gpl-2.0.htm GNU/GPL, или help/license.php
 * JoiCaddy - свободное программное обеспечение распространяемое по условиям лицензии GNU/GPL
 * JoiCaddy основан на разработках SimpleCaddy от Henk von Pickartz
 */

defined('_VALID_MOS') or die();
$debug = 0;

defined('JPATH_BASE') or define('JPATH_BASE', $_SERVER['DOCUMENT_ROOT']);

if(is_file(JPATH_BASE . DS . 'components' . DS . 'com_caddy' . DS . 'caddy.class.php'))
    require_once (JPATH_BASE . DS . 'components' . DS . 'com_caddy' . DS . 'caddy.class.php');
else
    die('File caddy.class.php not found');

if(is_file(JPATH_BASE . DS . 'components' . DS . 'com_caddy' . DS . 'caddy.cart.class.php'))
    require_once (JPATH_BASE . DS . 'components' . DS . 'com_caddy' . DS . 'caddy.cart.class.php');
else
    die('File caddy.cart.class.php');

$_MAMBOTS->registerFunction('onPrepareContent', 'JoiCaddyBot');

global $mosConfig_lang;
$lang = ($mosConfig_lang == '') ? 'russian' : $mosConfig_lang;
if(is_file(JPATH_BASE . DS . 'mambots' . DS . 'content' . DS . 'joicaddy' . DS . 'lang' . DS . $lang . '.php'))
    require_once (JPATH_BASE . DS . 'mambots' . DS . 'content' . DS . 'joicaddy' . DS . 'lang' . DS . $lang . '.php');
else
    die('File ' . $lang . '.php not found');

class dis
{
    var $tsep;
    var $dsep;
    var $decs;
    var $currency;
    var $curralign;
    var $separator;

    function __construct()
    {
        $cfg = new sc_configuration();
        $this->tsep = $cfg->get('thousand_sep');
        $this->dsep = $cfg->get('decimal_sep');
        $this->decs = $cfg->get('decimals');
        $this->currency = $cfg->get('currency');
        $this->curralign = $cfg->get('curralign');
    }
}

function JoiCaddyBot($published, &$article) {
    global $mainframe, $database, $_MAMBOTS;

    $mainframe->addCSS(JPATH_SITE.'/mambots/content/joicaddy/joicaddybot.css');

    // check if param query has previously been processed
    if (!isset($_MAMBOTS->_content_mambot_params['JoiCaddyBot'])) {
        // load mambot params info
        $query = "SELECT params FROM #__mambots WHERE element = 'joicaddy' AND folder = 'content'";
        $database->setQuery($query);
        $database->loadObject($mambot);

        // save query to class variable
        $_MAMBOTS->_content_mambot_params['JoiCaddyBot'] = $mambot;
    }

    // pull query data from class variable
    $mambot = $_MAMBOTS->_content_mambot_params['JoiCaddyBot'];

    $botParams = new mosParameters($mambot->params);

    $regex = '/{(joicaddy)\s*(.*?)}/i';

    //get global params from config
    $parms = array();
    $matches = array();
    preg_match_all($regex, $article->text, $matches, PREG_SET_ORDER);
    foreach ($matches as $elm) {
        $line = str_replace("&nbsp;", " ", $elm[2]);
        $line = str_replace(" ", "&", $line);
        parse_str($line, $parms);
        if (isset($parms['category'])) {
            $html = getSCbyCategory($parms, $botParams, 1);
        }
        else {
            $html = getSCSingle($parms, $botParams, 1);
        }
        $article->text = preg_replace($regex, $html, $article->text, 1);
    }
    return true;
}

function getSCSingle($params, $botParams, $debugmode = 0)
{
    global $Itemid, $mainframe;
    $dis = new dis();
    //	printf("<pre>%s</pre>", print_r($botParams,1));
    $classsuffix = isset($params['classsfx']) ? $params['classsfx'] : "";
    $prodcode = $params['code'];
    $defaultqty = isset($params['defqty']) ? $params['defqty'] : 1; // default qty set in qty edit box
    $minqty = isset($params['minqty']) ? $params['minqty'] : 0;
    $strqties = isset($params['qties']) ? $params['qties'] : null;
    $checkoos = isset($params['checkoos']) ? $params['checkoos'] : 0;
    $picname = isset($params['picname']) ? $params['picname'] : "";
    $aqties = explode(",", $strqties);

    $db = database::getInstance();
    $query = "SELECT * FROM #__sc_products WHERE prodcode='$prodcode'";
    $db->setQuery($query)->loadObject($product);

    if (!$product) {
        $html = "<div class='sccart$classsuffix'>";
        $html .= sprintf(SC_BOT_PRODUCT_NOT_FOUND, $prodcode);
        $html .= "</div>";
        return $html;
    }

    if ($product->published == '0') {
        $html = "<div class='sccart$classsuffix'>";
        $html .= sprintf(SC_BOT_PRODUCT_NOT_PUBLISHED, $prodcode);
        $html .= "</div>";
        return $html;
    }

    if (!$db->query()) {
        echo "<script> alert('" . $db->getErrorMsg() . "'); window.history.go(-1); </script>\n";
        exit();
    }

    $amount = number_format($product->unitprice, $dis->decs, $dis->dsep, $dis->tsep);
    if ($dis->curralign == 1) {
        $amount = $dis->currency . "&nbsp;" . $amount;
    }
    else {
        $amount = $amount . "&nbsp;" . $dis->currency;
    }

    $qtyfield = "\n<input type='" . ($botParams->get('showquantity') ? 'text' : 'hidden') . "' name='edtqty' value='$defaultqty' class='scp_qty$classsuffix' />";

    if ($strqties) { // specific quantities given
        $qtyfield = "<select name='edtqty' class='scp_selectqty$classsuffix'>";
        foreach ($aqties as $key => $value) {
            $qtyfield .= "<option value='$value'>$value</option>";
        }
        $qtyfield .= "</select>";
    }

    if ($checkoos == 1) { // check for minimum quantitites/ out of stock
        if ($product->av_qty >= 1) { // product still available
            $atcbtn = "\n<span class='button'><input type='submit' name='submit' value='" . SC_BOT_ADD_TO_CART . "' class='button$classsuffix' /></span>";
        }
        else { // product quantity is 0
            $atcbtn = "\n<span class='button'><input type='submit' name='submit' value='" . SC_BOT_OUT_OF_STOCK . "' class='button$classsuffix' disabled='disabled' /></span>";
        }
    }
    else {
            $atcbtn = "\n<span class='button'><input type='submit' name='submit' value='" . SC_BOT_ADD_TO_CART . "' class='button$classsuffix' /></span>";
    }

    $product_optionstitle = (trim($product->options)) ? stripslashes($product->optionstitle) : '';

    $optionhtml = "<div class='cartoptions$classsuffix'>";

    if ($botParams->get('showcartoptionstitle'))
        $optionhtml .= "\n<div class='cartoptionstitle$classsuffix'>$product_optionstitle</div>";

    //add the options line here
    $hasoptions = 0;
    if (trim($product->options)) {
        $hasoptions = 1;
        $options = explode("\n", trim($product->options));
        switch ($product->showas) {
            case "1": // horizontal radio buttons
                foreach ($options as $key => $po) {
                    list($shorttext, $formula, $caption, $defselect) = explode(":", $po);
                    $id = md5($product->prodcode . $po . $picname);
                    $checked = "";
                    if (trim($defselect) == "default") $checked = " checked='checked' ";
                    $optionhtml .= "<input type='radio' name='edtoption' value='$id:$po' $checked />" . stripslashes($shorttext) . "\n";
                }
                break;
            case "4": // vertical radio buttons
                foreach ($options as $key => $po) {
                    list($shorttext, $formula, $caption, $defselect) = explode(":", $po);
                    $id = md5($product->prodcode . $po . $picname);
                    $checked = "";
                    if (trim($defselect) == "default") $checked = " checked='checked' ";
                    $optionhtml .= "\n<input type='radio' name='edtoption' value='$id:$po' $checked />" . stripslashes($shorttext);
                    $optionhtml .= " $caption<br />";
                }
                break;
            case "2": // dropdown list
                $optionhtml .= "<select name='edtoption'>\n";
                foreach ($options as $key => $po) {
                    list($shorttext, $formula, $caption, $defselect) = explode(":", $po);
                    $id = md5($product->prodcode . $po . $picname);
                    $checked = "";
                    if (trim($defselect) == "default") $checked = " selected='selected' ";
                    $optionhtml .= "<option value='$id:$po' $checked>" . stripslashes($shorttext) . " $caption</option>\n";
                }
                $optionhtml .= "</select>\n";
                break;
            case "3": // standard list
                $optionhtml .= "<div class='scoptionselect$classsuffix'><select name='edtoption' size='10'>\n";
                foreach ($options as $key => $po) {
                    list($shorttext, $formula, $caption, $defselect) = explode(":", $po);
                    $id = md5($product->prodcode . $po . $picname);
                    $checked = "";
                    if (trim($defselect) == "default") $checked = " selected='selected' ";
                    $optionhtml .= "<option value='$id:$po' $checked>" . stripslashes($shorttext) . " $caption</option>\n";
                }
                $optionhtml .= "</select></div>\n";
                break;
            case "5": // free text
                $optionhtml .= "<input type='text' name='edtoption'>\n";
                $optionhtml .= "<input type='hidden' name='edtoption2' value='hidden'>\n";
                break;
            default:
                $optionhtml .= "";
        }
    }
    else
    { // product without options - generate id from productcode
        $id = md5($product->prodcode . $picname);
        $optionhtml .= "\n<input type='hidden' value='$id' name='edtoption' />";
    }
    $optionhtml .= "</div>";

    $html = "\n<div class='sccart$classsuffix'>";
    $html .= "\n<form name='addtocart$product->id' action='index.php' method='post'>";

    if ($botParams->get('showproductcodetext'))
        $html .= "\n<div class='scproduct$classsuffix'>" . SC_BOT_PRODUCT . " " . $dis->separator . "</div>";
    if ($botParams->get('showproductcode'))
        $html .= "\n<div class='scprodcode$classsuffix'>$product->prodcode $dis->separator</div>";
    if ($botParams->get('showtitle'))
        $html .= "\n<div class='scshorttext$classsuffix'>" . stripslashes($product->shorttext) . " $dis->separator</div>";
    if ($botParams->get('showunitpricetext'))
        $html .= "\n<div class='scunitpricetext$classsuffix'>" . SC_BOT_PRICE_PER_UNIT . " " . $dis->separator . "</div>";
    if ($botParams->get('showunitprice'))
        $html .= "\n<div class='scunitprice$classsuffix'>$amount $dis->separator</div>";
    if ($botParams->get('showquantitytext'))
        $html .= "\n<div class='scqtytext$classsuffix'>" . SC_BOT_QUANTITY . " " . $dis->separator . "</div>";

    $html .= "\n<div class='scqty$classsuffix'>$qtyfield $dis->separator</div>";
    $html .= "\n$optionhtml";
    $html .= "\n<div class='atczone$classsuffix'>$atcbtn</div>";
    $html .= "\n<input type='hidden' name='edtprodcode' value='$product->prodcode' />";
    $html .= "\n<input type='hidden' name='edtshorttext' value='$product->shorttext' />";
    $html .= "\n<input type='hidden' name='edtunitprice' value='$product->unitprice' />";
    $html .= "\n<input type='hidden' name='option' value='com_caddy' />";
    $html .= "\n<input type='hidden' name='action' value='addtocart' />";
    $html .= "\n<input type='hidden' name='picname' value='$picname' />";
    $html .= "\n<input type='hidden' name='Itemid' value='$Itemid' />";

    if ($minqty > 0) { // check for minimum quantity in the component
        $html .= "\n<input type='hidden' name='minqty' value='$minqty' />";
    }

    if ($botParams->get('stayonpage') == 1) {
        $html .= "\n<input type='hidden' name='lasturl' value='" . urlencode($_SERVER['REQUEST_URI']) . "' />";
        $html .= "\n<input type='hidden' name='stayonpage' value='1' />";
    }
    $html .= "\n</form>";
    $html .= "</div>";

    return $html;
}

function getSCbyCategory($params, $botParams, $debugmode = 0)
{
    global $Itemid, $mainframe;
    $dis = new dis();
    //printf("<pre>%s</pre>", print_r($plgParams,1));
    $category = $params['category'];
    $defaultqty = isset($params['defqty']) ? $params['defqty'] : 1;
    $classsuffix = isset($params['classsfx']) ? $params['classsfx'] : "";
    $checkoos = isset($params['checkoos']) ? $params['checkoos'] : 0;

    $db = database::getInstance();
    $query = "SELECT * FROM #__sc_products WHERE category='$category' and `published`=1";
    $lstproduct = $db->setQuery($query)->loadObjectList();

    if (!$lstproduct) {
        $html = "<div class='sccart$classsuffix'>";
        $html .= "<h3>The category ($category) is not found.</h3>";
        $html .= "</div>";
        return $html;
    }

    if (!$db->query()) {
        echo "<script> alert('" . $db->getErrorMsg() . "'); window.history.go(-1); </script>\n";
        exit();
    }
    $html = "";

    foreach ($lstproduct as $product) {

        $amount = number_format($product->unitprice, $dis->decs, $dis->dsep, $dis->tsep);
        if ($dis->curralign == 1) {
            $amount = $dis->currency . "&nbsp;" . $amount;
        }
        else {
            $amount = $amount . "&nbsp;" . $dis->currency;
        }

        $qtyfield = "\n<input type='" . ($botParams->get('showquantity') ? 'text' : 'hidden') . "' name='edtqty' value='$defaultqty' class='scp_qty$classsuffix' />";

        if ($checkoos == 1) { // check for minimum quantitites/ out of stock
            if ($product->av_qty >= 1) { // product still available
                $atcbtn = "\n<span class='button'><input type='submit' name='submit' value='" . SC_BOT_ADD_TO_CART . "' class='button$classsuffix' /></span>";
            }
            else { // product quantity is 0
                $atcbtn = "\n<span class='button'><input type='submit' name='submit' value='" . SC_BOT_OUT_OF_STOCK . "' class='button$classsuffix' disabled='disabled' /></span>";
            }
        }
        else {
                $atcbtn = "\n<span class='button'><input type='submit' name='submit' value='" . SC_BOT_ADD_TO_CART . "' class='button$classsuffix' /></span>";
        }

        $product_optionstitle = (trim($product->options)) ? stripslashes($product->optionstitle) : '';

        $optionhtml = "<div class='cartoptions$classsuffix'>";

        if ($botParams->get('showcartoptionstitle'))
            $optionhtml .= "\n<div class='cartoptions$classsuffix'>$product_optionstitle</div>";

        //add the options line here
        $hasoptions = 0;
        if (trim($product->options)) {
            $hasoptions = 1;
            $options = explode("\n", trim($product->options));
            switch ($product->showas) {
                case "1": // radio buttons
                    foreach ($options as $key => $po) {
                        @list($shorttext, $formula, $caption, $defselect) = explode(":", $po);
                        $id = md5($product->prodcode . $po);
                        $checked = "";
                        if (trim($defselect) == "default") $checked = " checked='checked' ";
                        $optionhtml .= "<input type='radio' name='edtoption' value='$id:$po' $checked />" . stripslashes($shorttext) . "\n";
                    }
                    break;
                case "4": // vertical radio buttons
                    foreach ($options as $key => $po) {
                        @list($shorttext, $formula, $caption, $defselect) = explode(":", $po);
                        $id = md5($product->prodcode . $po);
                        $checked = "";
                        if ($defselect == "default") $checked = " checked='checked' ";
                        $optionhtml .= "\n<input type='radio' name='edtoption' value='$id:$po' $checked />" . stripslashes($shorttext);
                        $optionhtml .= " $caption<br />";
                    }
                    break;
                case "2": // dropdown list
                    $optionhtml .= "<select name='edtoption'>\n";
                    foreach ($options as $key => $po) {
                        @list($shorttext, $formula, $caption, $defselect) = explode(":", $po);
                        $id = md5($product->prodcode . $po);
                        $checked = "";
                        if ($defselect == "default") $checked = " selected='selected' ";
                        $optionhtml .= "<option value='$id:$po' $checked>" . stripslashes($shorttext) . " $caption</option>\n";
                    }
                    $optionhtml .= "</select>\n";
                    break;
                case "3": // standard list
                    $optionhtml .= "<select name='edtoption' size='10'>\n";
                    foreach ($options as $key => $po) {
                        @list($shorttext, $formula, $caption, $defselect) = explode(":", $po);
                        $id = md5($product->prodcode . $po);
                        $checked = "";
                        if ($defselect == "default") $checked = " selected='selected' ";
                        $optionhtml .= "<option value='$id:$po' $checked>" . stripslashes($shorttext) . " $caption</option>\n";
                    }
                    $optionhtml .= "</select>\n";
                    break;
                case "5": // free text
                    $optionhtml .= "<input type='text' name='edtoption'>\n";
                    $optionhtml .= "<input type='hidden' name='edtoption2' value='hidden'>\n";
                    break;
                default:
                    $optionhtml .= "";
            }
        }
        else
        { // product without options - generate id from productcode
            $id = md5($product->prodcode);
            $optionhtml .= "\n<input type='hidden' value='$id' name='edtoption' />";
        }
        $optionhtml .= "</div>";

        $html .= "\n<form name='addtocart$product->id' action='index.php' method='post'>";
        $html .= "\n<div class='sccart$classsuffix'>";
        if ($botParams->get('showproductcodetext'))
            $html .= "\n<div class='scproduct$classsuffix'>" . SC_BOT_PRODUCT . " " . $dis->separator . "</div>";
        if ($botParams->get('showproductcode'))
            $html .= "\n<div class='scprodcode$classsuffix'>$product->prodcode $dis->separator</div>";
        if ($botParams->get('showtitle'))
            $html .= "\n<div class='scshorttext$classsuffix'>" . stripslashes($product->shorttext) . " $dis->separator</div>";
        if ($botParams->get('showunitpricetext'))
            $html .= "\n<div class='scunitpricetext$classsuffix'>" . SC_BOT_PRICE_PER_UNIT . " " . $dis->separator . "</div>";
        if ($botParams->get('showunitprice'))
            $html .= "\n<div class='scunitprice$classsuffix'>$amount $dis->separator</div>";
        if ($botParams->get('showquantitytext'))
            $html .= "\n<div class='scqtytext$classsuffix'>" . SC_BOT_QUANTITY . " " . $dis->separator . "</div>";
        $html .= "\n<div class='scqty$classsuffix'>$qtyfield $dis->separator</div>";
        $html .= "\n$optionhtml";
        $html .= "\n<div class='atczone$classsuffix'>$atcbtn</div>";
        $html .= "\n<input type='hidden' name='edtprodcode' value='$product->prodcode' />";
        $html .= "\n<input type='hidden' name='edtshorttext' value='$product->shorttext' />";
        $html .= "\n<input type='hidden' name='edtunitprice' value='$product->unitprice' />";
        $html .= "\n<input type='hidden' name='option' value='com_caddy' />";
        $html .= "\n<input type='hidden' name='action' value='addtocart' />";
        if ($botParams->get('stayonpage') == 1) {
            $html .= "\n<input type='hidden' name='lasturl' value='" . urlencode($_SERVER['REQUEST_URI']) . "' />";
            $html .= "\n<input type='hidden' name='stayonpage' value='1' />";
        }
        $html .= "\n<input type='hidden' name='Itemid' value='$Itemid' />";
        $html .= "</div>";
        $html .= "\n</form>";
    }
    return $html;
}


?>